<?php

function get_sql($sqlFilePath = null,$prefix = 'bs_')
{
    $sqlFilePath = $sqlFilePath ? $sqlFilePath : ROOT_PATH . 'install/bs_shop.sql';
    // 打开文件
    $fileHandle = fopen($sqlFilePath, 'r');
    $sqlStatements = '';
    // 用于存储当前正在构建的SQL语句
    $currentSql = '';
    // 逐行读取文件
    while (($line = fgets($fileHandle)) !== false) {
        // 去除行尾的换行符
        $line = trim($line);
        // 使用正则表达式移除以 '--' 开头的注释行
        if (preg_match('/^\-\-.*/', $line)) {
            continue;
        }
        // 移除空白行
        if (preg_match('/^\s*$/', $line)) {
            // 如果当前正在构建的SQL语句不为空，且当前行为空白行，则将当前构建的SQL语句添加到结果数组中
            if (!empty($currentSql)) {
                $sqlStatements .= $currentSql . ';' . "\n";
                $currentSql = ''; // 重置当前SQL语句
            }
            continue;
        }
        // 将当前行添加到当前正在构建的SQL语句中
        $currentSql .= $line . ' ';
        // 检查是否是SQL语句的结束
        if (preg_match('/;\s*(--.*)?$/', $line)) {
            // 如果是语句的结束，将其添加到结果数组中
            $sqlStatements .= rtrim($currentSql) . ';' . "\n";
            $currentSql = ''; // 重置当前SQL语句
        }
    }
    if (!empty($currentSql)) {
        $sqlStatements .= rtrim($currentSql) . ';';
    }
    fclose($fileHandle);
    $sqlArray = explode("\n", str_replace(";;", ';', $sqlStatements));
    foreach ($sqlArray as $key=> $sql) {
        if (preg_match('/`(\w+)`/', $sql, $matches)) {
            // 替换第一个匹配的表名
            $sqlArray[$key] = preg_replace('/`(\w+)`/', '`' . $prefix . '$1`', $sql, 1);
        }
    }
    return $sqlArray;
}

header("Content-type: text/html; charset=utf-8");
@set_time_limit(1800) || @ini_set('max_execution_time', '1800');
$str = '';
$err = 0;
if (version_compare(PHP_VERSION, '5.5.0', '<')) {
    $str .= "<span class='ss-red'> php版本过低，目前版本：" . phpversion() . "，支持php版本5.5+  X</span><br>";
    $err++;
} else {
    $str .= "<span class='ss-green'> php版本：" . phpversion() . ">= 5.5.0 √</span><br>";
}
if (!class_exists('PDO')) {
    $str .= "<span class='ss-red'> 系统未安装PDO扩展，请先安装PDO。  X</span><br>";
    $err++;
} else {
    $str .= "<span class='ss-green'> PDO扩展正常 √</span><br>";
}
if (!is_writable(ROOT_PATH)) {
    $str .= "<span class='ss-red'> 需要配置.env环境，" . str_replace('\\', '/', ROOT_PATH) . "需要可写权限  X</span><br>";
    $err++;
} else {
    $str .= "<span class='ss-green'> " . str_replace('\\', '/', ROOT_PATH) . "可写权限  √</span><br>";
}
if (!file_exists(ROOT_PATH . 'install/bs_shop.sql')) {
    $str .= "<span class='ss-red'> install/bs_shop.sql不存在，代码不完整！  X</span><br>";
    $err++;
}

if (!empty($_POST['from']) && $_POST['from'] === 'dbConf') {

    $t = ['dbLink' => '数据库地址', 'dbName' => '数据库名未填写', 'dbPort' => '数据库端口未填写', 'uName' => '数据库用户名未填写', 'uPwd' => '用户密码未填写'];
    $tt = '';
    foreach ($t as $key => $text) {
        if (empty($_POST[$key])) {
            $tt = "<span class='ss-red'>$text</span>";
            break;
        }
    }
    if ($tt) {
        $str .= $tt;
    } else {
        $doing = 1;
        $host = trim($_POST['dbLink']);
        $dbName = trim($_POST['dbName']);
        $userName = trim($_POST['uName']);
        $userPwd = trim($_POST['uPwd']);
        $prefix = !empty($_POST['prefix']) ? trim($_POST['prefix']) : "bs_";
        $port = intval($_POST['dbPort']);
        $charset = trim($_POST['charset']);
        $link = @mysqli_connect($host, $userName, $userPwd, $dbName, $port);
        if (!$link) {
            $str .= "<span class='ss-red'>数据库无法连接，请检查数据库配置：</span><br>";
            $str .= "<span class='ss-red'>" . mysqli_connect_error() . "</span><br>";
        } else {
            mysqli_close($link);
            $str .= "<span class='ss-green'>数据库账号密码可用 √</span><br>";
            $env = <<<doc
APP_DEBUG = false
APP_TRACE = false

[database]
type = mysql
HOSTNAME = {$host}
DATABASE = {$dbName}
USERNAME = {$userName}
PASSWORD = {$userPwd}
CHARSET = {$charset}
HOSTPORT = {$port}
PREFIX = {$prefix}
doc;

            //写入env配置
            $x = @file_put_contents(ROOT_PATH . '.env', $env);
            $arr = get_sql(ROOT_PATH . 'install/bs_shop.sql',$prefix);
            foreach ($arr as &$item) {
                $item = preg_replace('/\s+/', ' ', $item);
                if ($charset === 'utf8') {
                    $item = str_replace('utf8mb4', 'utf8', $item);
                }
                /*if (stripos($item, 'DROP TABLE IF EXISTS `')) {
                    $item = str_replace('DROP TABLE IF EXISTS `', 'DROP TABLE IF EXISTS `' . $prefix, $item);
                }
                if (stripos($item, 'CREATE TABLE `')) {
                    $item = str_replace('CREATE TABLE `', 'CREATE TABLE `' . $prefix, $item);
                }
                if (stripos($item, 'INSERT INTO `')) {
                    $item = str_replace('INSERT INTO `', 'INSERT INTO `' . $prefix, $item);

                }*/
                $item = $item . ';';
                if (is_writable(__DIR__ . '/')) {
                    file_put_contents(__DIR__ . '/install.log', $item . PHP_EOL, FILE_APPEND);
                }
            }
            $dsn = 'mysql:host=' . $host . ';dbname=' . $dbName . ';charset=' . $charset;
            try {
                PDO::ATTR_TIMEOUT;
                $link = new PDO($dsn, $userName, $userPwd);
                $link->exec('alter database ' . $dbName . ' CHARACTER SET ' . $charset);
                foreach ($arr as $sql) {
                    $link->exec($sql);
                }
                $r = @$link->exec("INSERT INTO " . $prefix . "config (`key`,`value`) VALUES ('test','ok')");
                if ($r) {
                    $link->exec("DELETE FROM " . $prefix . "config where `key`='test' ");
                } else {
                    $str .= '<span class="ss-red">数据库配置异常</span><br>';
                }

                @file_put_contents(ROOT_PATH . 'install.lock', "安装完成时间:" . date('Y-m-d H:i:s') . "\r\n要重新安装请删除本文件。");
                header("Location:http://" . $_SERVER['HTTP_HOST'] . '/admin');
            } catch (PDOException $e) {
                $str .= "<span class='ss-red'>数据库登录失败：" . $e->getMessage() . " </span>";
            }
        }
    }
}
?>
<!doctype html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>

    <title>安装配置</title>
    <style>
        .btn-group {
            margin-top: 10px;
        }

        .ss-red {
            color: red
        }

        .ss-green {
            color: green
        }

        .ss-orange {
            color: orange
        }
    </style>
</head>
<body style="margin: 10px">
<div class="container">
    <div class="row">
        <div class="span12">
            <h3>安装BS-SHOP商城</h3>
            <p style="color: red">
                安装会执行数据库重新配置，若您已手动安装请在根目录添加install.lock文件，或者在public/base.php去掉安装检测。要重新安装请删除根目录的install.lock文件。</p>
            <p style="color: blue">如何超时请设置php的超时时间，一般一分钟内完成。</p>
            <p style="color: blue">安装完成后后台（http://xxxx/admin 账号密码：bsshop 123456</p>
            <p>
                <small>php+mysql</small>
                <br>
                <?php echo $str; ?>
            </p>
            <h1 class="donig" style="color: red"></h1>
            <form class="form-horizontal" method="post">
                <input type="hidden" name="from" value="dbConf">
                <div class="control-group">
                    <label class="control-label" for="dbName">数据库名称</label>
                    <div class="controls">
                        <input id="dbName" autocomplete="off" placeholder="请输入数据库名称" class="form-control"
                               style="width: 250px" type="text" name="dbName"
                               value="<?php echo !empty($dbName) ? $dbName : 'bs_shop' ?>"/>
                    </div>
                </div>
                <div class="control-group">
                    <label class="control-label" for="dbLink">数据库地址</label>
                    <div class="controls">
                        <input id="dbLink" autocomplete="off" placeholder="请输入数据库地址" class="form-control"
                               style="width: 250px" type="text" name="dbLink"
                               value="<?php echo !empty($host) ? $host : '127.0.0.1' ?>"/>
                    </div>
                </div>
                <div class="control-group">
                    <label class="control-label" for="dbPort">数据库端口</label>
                    <div class="controls">
                        <input id="dbPort" autocomplete="off" placeholder="请输入数据库端口" class="form-control"
                               style="width: 100px" type="number" name="dbPort"
                               value="<?php echo !empty($port) ? $port : '3306' ?>"/>
                    </div>
                </div>
                <div class="control-group">
                    <label class="control-label" for="dbCharSet">数据库编码</label>
                    <div class="controls">
                        <select name="charset" class="form-control" style="width: 250px" id="dbCharSet">
                            <option value="utf8mb4">utf8mb4(推荐)</option>
                            <option value="utf8">utf8</option>
                        </select>
                        <span class="ss-orange">若和实际数据库编码不符合，则系统会自动修改数据库的编码，请认真核实!</span>
                    </div>
                </div>
                <div class="control-group">
                    <label class="control-label" for="prefix">数据表前缀</label>
                    <div class="controls">
                        <input id="prefix" autocomplete="off" placeholder="请输入数据表前缀" class="form-control"
                               style="width: 100px" type="text" name="prefix"
                               value="<?php echo !empty($prefix) ? $prefix : 'bs_' ?>"/>
                    </div>
                </div>
                <div class="control-group">
                    <label class="control-label" for="uName">数据库用户名</label>
                    <div class="controls">
                        <input id="uName" autocomplete="off" placeholder="请输入数据库用户名称" style="width: 250px"
                               class="form-control" type="text" name="uName"
                               value="<?php echo !empty($userName) ? $userName : 'root' ?>"/>
                    </div>
                </div>
                <div class="control-group">
                    <label class="control-label" for="inputPassword">数据库密码</label>
                    <div class="controls">
                        <input id="inputPassword" autocomplete="off" placeholder="请输入数据库密码" style="width: 250px"
                               class="form-control" type="password" name="uPwd"
                               value="<?php echo !empty($userPwd) ? $userPwd : 'root' ?>"/>
                    </div>
                </div>
                <div class="control-group">
                    <div class="controls btn-group">
                        <button onclick="showDoing()" type="submit" class="btn btn-success start-btn">安装</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<script>
    function showDoing() {

        $(".start-btn").hide();
        let i = 0;
        setInterval(function () {
            i++
            $(".donig").empty().html('进行中，请勿操作其他' + i)
        }, 1000)
    }

</script>
</body>
</html>
